<template>
  <div class="memory-analysis-chart">
    <div ref="chartRef" class="chart" v-loading="loading"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { formatBytes } from '@/utils/format'

const props = defineProps({
  moduleData: {
    type: Object,
    required: true
  }
})

const chartRef = ref(null)
const loading = ref(true)
let chartInstance = null

// 创建resize处理函数
const resizeHandler = () => {
  if (chartInstance && chartRef.value) {
    try {
      chartInstance.resize()
    } catch (error) {
      // 静默处理resize错误
    }
  }
}

const initChart = () => {
  if (!chartRef.value) return

  const container = chartRef.value

  // 如果已存在实例，先销毁
  if (chartInstance) {
    chartInstance.dispose()
  }

  // 强制设置明确的容器尺寸
  const containerRect = container.getBoundingClientRect()
  if (containerRect.width === 0 || containerRect.height === 0) {
    const parentRect = container.parentElement?.getBoundingClientRect()
    if (parentRect && parentRect.width > 0) {
      container.style.width = `${parentRect.width}px`
    } else {
      container.style.width = '100%'
    }
    container.style.height = '300px'
    container.style.display = 'block'
    container.style.overflow = 'hidden'
  }

  try {
    // 使用明确的尺寸初始化ECharts
    const containerWidth = container.clientWidth || 800
    const containerHeight = container.clientHeight || 300

    chartInstance = echarts.init(container, null, {
      width: containerWidth,
      height: containerHeight
    })

    // 模拟内存分析数据 - 使用PSS内存数据作为基础
  const baseMemory = props.moduleData.pss || props.moduleData.size || 100000
  const memoryData = [
    { name: '__TEXT (代码段)', value: baseMemory * 0.35 },
    { name: '__DATA (数据段)', value: baseMemory * 0.25 },
    { name: '__LINKEDIT (链接信息)', value: baseMemory * 0.20 },
    { name: '__CONST (常量段)', value: baseMemory * 0.10 },
    { name: '__OBJC (ObjC数据)', value: baseMemory * 0.06 },
    { name: '其他段', value: baseMemory * 0.04 }
  ].filter(item => item.value > 1024) // 过滤掉小于1KB的段

  const option = {
    title: {
      text: '内存占用分析',
      textStyle: {
        fontSize: 16,
        fontWeight: 600,
        color: getComputedStyle(document.documentElement).getPropertyValue('--el-text-color-primary').trim() || '#303133'
      },
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        return `${params.name}: ${formatBytes(params.value)} (${params.percent}%)`
      },
      backgroundColor: getComputedStyle(document.documentElement).getPropertyValue('--el-bg-color').trim() || '#ffffff',
      borderColor: getComputedStyle(document.documentElement).getPropertyValue('--el-border-color-lighter').trim() || '#e4e7ed',
      textStyle: {
        color: getComputedStyle(document.documentElement).getPropertyValue('--el-text-color-primary').trim() || '#303133'
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      textStyle: {
        color: getComputedStyle(document.documentElement).getPropertyValue('--el-text-color-primary').trim() || '#303133'
      }
    },
    series: [
      {
        name: '内存分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold',
            color: getComputedStyle(document.documentElement).getPropertyValue('--el-text-color-primary').trim() || '#303133'
          }
        },
        labelLine: {
          show: false
        },
        data: memoryData.map((item, index) => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: [
              '#5470c6',
              '#91cc75',
              '#fac858',
              '#ee6666',
              '#73c0de',
              '#3ba272'
            ][index % 6]
          }
        }))
      }
    ]
  }

  chartInstance.setOption(option)

  } catch (error) {
    // 如果初始化失败，创建一个简单的占位符
    container.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 300px; color: #999;">内存分析图表加载中...</div>'
  }
}

// 监听moduleData变化
watch(() => props.moduleData, () => {
  if (chartInstance) {
    initChart()
  }
}, { deep: true })

// 监听主题变化
const handleThemeChange = () => {
  if (chartInstance) {
    initChart()
  }
}

onMounted(() => {
  // 添加resize监听器
  if (typeof window !== 'undefined') {
    window.addEventListener('resize', resizeHandler)

    // 监听主题变化
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addEventListener('change', handleThemeChange)

    // 监听Element Plus主题变化
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
          handleThemeChange()
        }
      })
    })

    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['class']
    })
  }

  // 使用 nextTick 确保 DOM 完全渲染后再初始化
  nextTick(() => {
    // 再加一个短延迟确保标签页完全渲染
    setTimeout(() => {
      loading.value = false
      initChart()
    }, 100)
  })
})

onUnmounted(() => {
  // 清理ECharts实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }

  // 清理resize监听器
  if (typeof window !== 'undefined') {
    window.removeEventListener('resize', resizeHandler)

    // 清理主题变化监听器
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.removeEventListener('change', handleThemeChange)
  }
})
</script>

<style scoped lang="scss">
.memory-analysis-chart {
  width: 100%;
  height: 100%;
  min-height: 300px;
  position: relative;

  .chart {
    width: 100% !important;
    height: 100% !important;
    min-height: 300px !important;
    display: block !important;
    position: absolute !important;
    top: 0 !important;
    left: 0 !important;
  }
}
</style>